import React, { Component } from 'react';
import { Row, Col, Input, Select, Button, Form, DatePicker } from 'antd';
import '../../customerCenter/customer.css';
import HasPermission, { testPermission } from '../../common/HasPermission';
import api from '../../../api/api';
const { RangePicker } = DatePicker;
class CheckSearch extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checkPackList: [{}], // 体检套餐列表
      queryTextPlaceholder: '请输入姓名',
    };
  }

  componentWillMount() {
    this.getCheckPackList(); // 获取体检套餐列表
  }

  // 获取保险产品列表
  getCheckPackList = async () => {
    let checkPackList = (await api.queryPackages()) || [{}];
    checkPackList = checkPackList.map((item) => {
      return {
        value: String(item.id),
        label: item.title,
      };
    });
    this.setState({
      checkPackList,
    });
  };

  // 提交数据
  submitForm = (event) => {
    event.preventDefault();
    let formValues = this.props.form.getFieldsValue();

    formValues[formValues.queryKey] = formValues.queryText;
    delete formValues.queryKey;
    delete formValues.queryText;

    if (formValues.uploadDate) {
      formValues.uploadDate = formValues.uploadDate.map((moment) => moment.format('YYYY-MM-DD'));
      formValues.createStart = formValues.uploadDate[0];
      formValues.createEnd = formValues.uploadDate[1];
      delete formValues.uploadDate;
    }
    for (let item in formValues) {
      if (formValues[item] === '') {
        delete formValues[item];
      }
    }

    this.props.searchDataFn(formValues, true);
  };
    exportList = () => {
    let formValues = this.props.form.getFieldsValue();
    formValues[formValues.queryKey] = formValues.queryText;
    delete formValues.queryKey;
    delete formValues.queryText;
    if (formValues.uploadDate) {
      formValues.uploadDate = formValues.uploadDate.map((moment) => moment.format('YYYY-MM-DD'));
      formValues.createStart = formValues.uploadDate[0];
      formValues.createEnd = formValues.uploadDate[1];
      delete formValues.uploadDate;
    }
    for (let item in formValues) {
      if (formValues[item] === '') {
        delete formValues[item];
      }
    }
    let urlStr = '';
    Object.keys(formValues).forEach((key) => {
      if (formValues[key] && (urlStr.indexOf('?') === -1)) {
        urlStr += `?${key}=${formValues[key]}`;
      } else if(formValues[key] || formValues[key] === 0){
        urlStr += `&${key}=${formValues[key]}`;
      }
    })
    window.open(`_api/physicalExaminationOrders/export${urlStr}`);
  }
  render() {
    const queryKeyChoices = [
      {
        value: 'name',
        label: '服务对象',
        placeholder: '请输入服务对象',
      },
      {
        value: 'insuranceOrderNo',
        label: '服务单号',
        placeholder: '请输入服务单号',
      },
    ];

    const checkPackStatus = [
      { value: '10', label: '待激活' },
      { value: '99', label: '已完成' },
      { value: '98', label: '已终止' },
    ];

    const { getFieldDecorator } = this.props.form;
    const mapChoiceToOption = (choice, i) => (
      <Select.Option key={i} value={choice.value} title={choice.label}>
        {choice.label}
      </Select.Option>
    );
    const dateFormat = 'YYYY-MM-DD';

    let that = this;
    function changeQueryKey(value) {
      let queryTextPlaceholder = queryKeyChoices.find((item) => {
        return item.value === value;
      }).placeholder;
      that.setState({
        queryTextPlaceholder,
      });
    }

    return (
      <Form onSubmit={this.submitForm}>
        <Row gutter={10} className="block filter-box">
          <Col span={3} key="1">
            <Form.Item height="auto">
              {getFieldDecorator('queryKey', {
                initialValue: queryKeyChoices[0].value,
              })(<Select onChange={changeQueryKey.bind(this)}>{queryKeyChoices.map(mapChoiceToOption)}</Select>)}
            </Form.Item>
          </Col>

          <Col span={3} key="2">
            <Form.Item height="auto">
              {getFieldDecorator('queryText')(<Input placeholder={this.state.queryTextPlaceholder} />)}
            </Form.Item>
          </Col>

          <Col span={3} key="3">
            <Form.Item height="auto">
              {getFieldDecorator(
                'cardPackageId',
                {},
              )(
                <Select placeholder="请选择体检套餐" allowClear>
                  {this.state.checkPackList.map(mapChoiceToOption)}
                </Select>,
              )}
            </Form.Item>
          </Col>

          <Col span={3} key="4">
            <Form.Item height="auto">
              {getFieldDecorator(
                'status',
                {},
              )(
                <Select placeholder="请选择体检单状态" allowClear>
                  {checkPackStatus.map(mapChoiceToOption)}
                </Select>,
              )}
            </Form.Item>
          </Col>

          <Col span={6} key="5">
            <Form.Item height="auto">
              {getFieldDecorator(
                'uploadDate',
                {},
              )(<RangePicker format={dateFormat} placeholder={['创建开始时间', '创建结束时间']} />)}
            </Form.Item>
          </Col>

          <Col span={2}>
            <Form.Item>
              <Button style={{ width: '100%', minWidth: 0 }} type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Col>
          {testPermission('physicalExaminationOrders.export')?<Col span={2}>
            <Form.Item>
              <Button style={{ width: '100%', minWidth: 0 }} type="primary" onClick={ () => this.exportList() }>
                导出
              </Button>
            </Form.Item>
        </Col> : null}
        </Row>
      </Form>
    );
  }
}

export default Form.create({})(CheckSearch);
